<template>
  <el-skeleton :loading="loading">
    <div class="batch-btns">
      <div v-if="timesList.length">
        <el-button type="text" @click="batchAddHandout" >批量添加讲义</el-button>
        <el-button type="text" @click="batchDeleteHandout">清空添加讲义</el-button>
      </div>
    </div>
    <div class="class-times-container" v-if="timesList.length">
      <!--     github issue  https://github.com/SortableJS/vue.draggable.next/issues/140     -->
      <draggable :modelValue="timesList" @update:modelValue="dragSortHandle" animation="250" item-key="id">
        <template #item="{ element, index }">
          <DataComponent :data="element" :index="index" />
        </template>
      </draggable>
    </div>
    <EmptyComponent v-else />
  </el-skeleton>
</template>

<script lang="ts">
import { inject, computed, onUnmounted } from 'vue'
import draggable from 'vuedraggable';
import EmptyComponent from './components/empty.vue';
import DataComponent from './components/data.vue';
import AddHandoutComponent from './components/add-handout.vue';
import $ from '$';
import store from './store';
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  components: { draggable, DataComponent, EmptyComponent },
  setup() {
    let planInfo = inject<Function>('getPlanInfo')!();

    let timesList = computed(() => store.state.timesList);

    let [ loading, setLoading ] = $.useState(false);

    const getClassTimes = (() => {
      let fn = () => {
        setLoading(true);
        $.http.post('/admin/teachTimes/query', { planId: planInfo.id }).then(res => store.commit('set_times_list', res.json)).finally(() => setLoading(false));
      }; fn();
      return fn;
    })();

    const dragSortHandle = async (list) => {
      let params = list.map((data, idx) => ({ id: data.id, sortNum: idx + 1 }));
      let res = await $.http.json('/admin/teachTimes/batchUpdate', params);
      res.result && getClassTimes();
    }

    const __postMessageFn = ({ origin, data }) => origin === window.location.origin && data.type === 'handout-save-success' && getClassTimes();
    window.addEventListener('message', __postMessageFn);
    onUnmounted(() => window.removeEventListener('message', __postMessageFn));

    $.emitter.on('class-times-change', getClassTimes);

    const batchAddHandout = async() => {
      let title = '批量添加标准讲义';
      let result = await $.drawer.create({ title, width: 1080, zIndex: 2016, component: AddHandoutComponent, props: { isBatch: true, timesList: timesList.value } });
      let batchSaveParam = result.map((e, idx) => {
        if (result[idx]) {
          return Object.assign({}, { indexId: timesList.value[idx].id, type: e.filePath ? 1 : 2, handoutId: e.id })
        }
      })
      let batchEditName = result.map((e, idx) => {
        if (result[idx]) {
          return Object.assign({}, { indexName: e.fileName, id: timesList.value[idx].id })
        }
      })
      let res = await $.http.json('/admin/teachTimesHandoutRelation/batchSave', batchSaveParam);//批量添加讲义
      let nameRes = await $.http.json('/admin/teachTimes/batchUpdate', batchEditName);//批量修改课次名称
      !nameRes.result && ElMessage.warning(nameRes.msg)
      $.utils.message(res.result, title);
      $.emitter.emit('class-times-change');
    }
    const batchDeleteHandout = async() => {
      let list = timesList.value.filter(e => e.child)
      let deleteParam = list.map(e => e.id)
      await ElMessageBox.confirm('确认解绑所有标准讲义吗？', { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' });
      let res = await $.http.json(`/admin/teachTimesHandoutRelation/batchDeleteByIndex`, deleteParam);
      if (deleteParam.length) {
        $.utils.message(res.result, '解绑标准讲义');
        $.emitter.emit('class-times-change');
      } else {
        ElMessage.warning('暂无讲义需要清空')
      }
    }
    return { timesList, loading, dragSortHandle, batchAddHandout, batchDeleteHandout }
  }
}
</script>
<style lang="scss" scoped>
  .batch-btns {
    display: flex;
    & > div {
      margin-left: auto;
    }
  }
</style>
